package com.sheng.leetcode.year2022.swordfingeroffer.day06;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liusheng
 * @date 2022/09/06
 *
 * 剑指 Offer 32 - III. 从上到下打印二叉树 III
 *
 * 请实现一个函数按照之字形顺序打印二叉树，即第一行按照从左到右的顺序打印，第二层按照从右到左的顺序打印，第三行再按照从左到右的顺序打印，其他行以此类推。
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回其层次遍历结果：
 * [
 *   [3],
 *   [20,9],
 *   [15,7]
 * ]
 *
 * 提示：
 *
 * 节点总数 <= 1000
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Sword0032Three {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(3);
        TreeNode right = new TreeNode(20);
        right.left = new TreeNode(15);
        right.right = new TreeNode(7);
        root.left = new TreeNode(9);
        root.right = right;
        System.out.println(new Solution32Three().levelOrder(root));
    }
}
class Solution32Three {

    List<List<Integer>> lists;
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        lists = new ArrayList<>();
        List<TreeNode> nodes = new ArrayList<>();
        List<Integer> integers = new ArrayList<>();
        nodes.add(root);
        integers.add(root.val);
        lists.add(integers);
        bfs(nodes, 1);
        return lists;
    }

    public void bfs(List<TreeNode> treeNodes, Integer num) {
        List<TreeNode> nodes = new ArrayList<>();
        List<Integer> integers = new ArrayList<>();
        for (TreeNode node : treeNodes) {
            if (node.left != null) {
                nodes.add(node.left);
            }
            if (node.right != null) {
                nodes.add(node.right);
            }
        }
        if (nodes.size() > 0) {
            if (num % 2 == 0) {
                for (TreeNode node : nodes) {
                    integers.add(node.val);
                }
            } else {
                for (int i = nodes.size() - 1; i >= 0; i--) {
                    integers.add(nodes.get(i).val);
                }
            }
            lists.add(integers);
            bfs(nodes, ++num);
        }
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
